﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using WebStudio.Business.Rule;
using WebStudio.Business.Entity;

public partial class Admin_ProductAdd : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

        if (Session["Admin_User"] == null || Session["Admin_User"].ToString() == "")
        {
            Response.Redirect("~/Admin/Login.aspx");
        }

        if (!Page.IsPostBack)
        {
            ddlParentNavBind();
            GetPhotoInfo();
        }
    }

    private PhotoEntity Info
    {
        get
        {
            if (string.IsNullOrEmpty(Request.QueryString["id"]))
            {
                return null;
            }
            else
            {
                try
                {
                    return PhotoRule.GetPhotoEntity(Convert.ToInt32(Request.QueryString["id"]));
                }
                catch
                {
                    return null;
                }
            }
        }
    }

    private void GetPhotoInfo()
    {
        PhotoEntity photoEntity = Info;
        if (photoEntity != null)
        {
            txtArticleName.Text = photoEntity.PhotoName;
            txtContent.Text = photoEntity.PhotoDescribe;
            int subId = AlbumRule.GetAlbumEntity(photoEntity.AlbumInfo.AlbumId).PAlbumInfo.AlbumId;
            ddlSubNavBind(subId);
            ddlSubNav.SelectedValue = photoEntity.AlbumInfo.AlbumId.ToString();
            ddlParentNav.SelectedValue = subId.ToString();
        }
    }

    private void ddlParentNavBind()
    {
        //ddlParentNav.DataSource = bCategory.GetParentList();
        ddlParentNav.DataSource = AlbumRule.GetParentAlbumlList(0);
        ddlParentNav.DataTextField = "AlbumName";
        ddlParentNav.DataValueField = "AlbumId";
        ddlParentNav.DataBind();
        ddlParentNav.Items.Insert(0, new ListItem("请选择...", "0"));
        ddlSubNav.Items.Insert(0, new ListItem("请选择...", "0"));
    }
    private void ddlSubNavBind(int id)
    {
        ddlSubNav.DataSource = AlbumRule.GetParentAlbumlList(id);
        ddlSubNav.DataTextField = "AlbumName";
        ddlSubNav.DataValueField = "AlbumId";
        ddlSubNav.DataBind();
    }

    protected void ddlParentNav_SelectedIndexChanged(object sender, EventArgs e)
    {
        int id = Convert.ToInt32(ddlParentNav.SelectedValue);
        if (id != 0)
        {
            ddlSubNavBind(id);
        }
        else
        {
            ddlSubNav.Items.Clear();
        }
        ddlSubNav.Items.Insert(0, new ListItem("请选择...", "0"));
    }

    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        string title = txtArticleName.Text.Trim();
        string content = txtContent.Text.Trim();
        string pCategory = ddlParentNav.SelectedValue;
        string category = ddlSubNav.SelectedValue;
        if (title == "")
        {
            return;
        }

        bool fileCheck = false;
        string filename = GenerateFileName();
        if (fuFrdLinks.HasFile)
        {
            //判断上传文件的格式
            string fileExtension = System.IO.Path.GetExtension(fuFrdLinks.FileName).ToLower();
            string[] allowExtension = { ".gif", ".jpg", ".bmp", ".png" };
            for (int i = 0; i < allowExtension.Length; i++)
            {
                if (fileExtension == allowExtension[i])
                {
                    fileCheck = true;
                    break;
                }
            }
            if (fileCheck == false)
            {
                ApplicationHelper.ShowClientMessage(this, "上传图片的格式不对！");
                return;
            }
            //判断上传文件的大小
            if (fuFrdLinks.PostedFile.ContentLength > 2048000)
            {
                fileCheck = false;
                ApplicationHelper.ShowClientMessage(this, "您上传的文件超过2M！");
                return;
            }
            //上面所有的条件都符合，则执行上传操作
            if (fileCheck)
            {
                try
                {
                    string strFilePath = Server.MapPath("~/Images/product/");
                    if (!Directory.Exists(strFilePath))
                    {
                        Directory.CreateDirectory(strFilePath);
                    }
                    string fileSavePath = strFilePath + filename + fileExtension;
                    filename = filename + fileExtension;
                    fuFrdLinks.SaveAs(fileSavePath);
                }
                catch (Exception ex)
                {
                    ApplicationHelper.ShowClientMessage(this, ex.Message);
                }
            }
        }
        else
        {
            //ApplicationHelper.ShowClientMessage(this, "没有要上传的文件！");
            filename = "";
        }


        PhotoEntity photoEntity = new PhotoEntity();
        photoEntity.PhotoName = title;

        photoEntity.AlbumInfo.AlbumId = Convert.ToInt32(category);
        if (photoEntity != null && filename == "")
        {
            photoEntity.PhotoUrl = Info.PhotoUrl;
        }
        else
        {
            photoEntity.PhotoUrl = "product/" + filename;
        }

        photoEntity.PhotoDescribe = txtContent.Text.Trim();
        
        if (Info == null)
        {
            photoEntity.CrtTime = DateTime.Now;
            if (PhotoRule.SavePhotoInfor(photoEntity))
            {
                //ArticalRule.SaveArticalInfor(articleEntity);
                ApplicationHelper.AddStartupScript(this, "if(confirm('添加成功，是否继续添加？')){location.href='ProductAdd.aspx';}else{location.href='ProductMge.aspx';}");
            }
            else
            {
                ApplicationHelper.AddStartupScript(this, "alert('添加失败！')");
            }
        }
        else
        {
            photoEntity.PhotoId = Convert.ToInt32(Request.QueryString["id"]);
            PhotoRule.SavePhotoInfor(photoEntity);
            ApplicationHelper.AddStartupScript(this, "alert('修改成功');location.href='ProductMge.aspx';");
        }
    }

    //生成文件名
    private string GenerateFileName()
    {
        return string.Format("{0}{1}", Guid.NewGuid().ToString().Substring(0, 4), DateTime.Now.ToString("yyyyssMMhhmmdd"));
    }
}
